import axios from 'axios'

type Result = {
    code: number;
    data: any;
    flag: boolean;
    message: string;
}

interface apiResult {
    code: number;
    data: any;
    flag: boolean;
    message: string;
}

const service = axios.create({
    headers: {"Content-Type": 'application/json;charset=UTF-8'},
    timeout: 30000,
    // baseURL: process.env.VUE_APP_BASE_API,
    // baseURL:"http://localhost:8086/",
})
service.interceptors.request.use(
    config => {
        const token = window.localStorage.getItem("token");
        if (token) {
            config.headers['Authorization'] = token
        }
        if (config.method === 'get' && config.params) {
            /* 过滤undefined */
            config.params = removeUndefined(config.params);
            /* 按店铺 */
            let currentShop = window.localStorage.getItem("currentShop");
            if (currentShop && !config.params.byLan) {
                config.params.shop = currentShop;
            }
            config.params = new URLSearchParams(config.params);
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
service.interceptors.response.use(
    (response): any => {
        const res = response.data
        if (res.code === 401) {
            window.location = '/login';
        }
        if (res.code !== 200) {
            return res
        }
        return res
    },
    (res) => {
        return {data: {}, code: 500, message: res.message};
    }
)

function removeUndefined(obj) {
    return Object.entries(obj)
        .filter(([_, value]) => value !== undefined)
        .reduce((acc, [key, value]) => {
            acc[key] = value;
            return acc;
        }, {});
}

export default service